<?php

namespace App\Models;

use Carbon\Carbon;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class ForeignSpeakerCollection extends Model
{
    // use SoftDeletes;
    use HasDateTimeFormatter;
    protected $table = 'eb_foreign_speaker_collection';

    protected $fillable = [
        'id',
        'name',
        'photo',
        'sort',
        'status',
        'user_id',
        'collection_id'
    ];

    /**
     * 一对多关联
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2022-08-17
     * @return void
     */
    public function collection_pivot()
    {
        return $this->hasMany(ForeignSpeakerCollectionPivot::class, 'collection_id', 'id');
    }

    public function collection_share()
    {
        return $this->hasMany(ForeignSpeakerShareLog::class, 'collection_id', 'id');
    }

    /**
     * 多对多
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2022-08-17
     * @return void
     */
    public function guest_collection_pivot()
    {
        return $this->belongsToMany(Speaker::class, 'eb_foreign_speaker_collection_pivot', 'collection_id', 'speaker_id')->withPivot('order', 'argument', 'like', 'user_id');
    }

    protected static function boot()
    {
        parent::boot();

        static::deleting(function ($collection) {
            $collection->collection_pivot()->delete();
            $collection->collection_share()->delete();
        });
    }

    /**
     * 获取列表
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2022-03-16
     * @param int $page
     * @param int $limit
     * @param array $where
     * @return mixed
     */
    public function getCollectionList($page, $limit, $where)
    {
        $userId = $where['user_id'];
        $where = function ($query) use ($where) {

            $query->where('user_id', $where['user_id']);
            $query->where('status', 1);

            if (isset($where['name']) && !empty($where['name'])) {
                $query->where('name', 'like', '%' . $where['name'] . '%');
            }
            // $query->where('is_del', 0);
            $share_ids = ForeignSpeakerShareLog::where('user_id', $where['user_id'])->pluck('collection_id');
            if (!empty($share_ids)) {
                $query->orWhereIn('id', $share_ids);
            }
        };


        $list = $this->where($where)
            ->select('id', 'name', 'user_id')
            ->orderBy('created_at', 'desc')
            ->paginate($limit);
        return $list;
    }


    /**
     * 获取列表(无分页)
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2022-03-16
     * @param array $where
     * @return mixed
     */
    public function getCollectionCateList($where)
    {
        $userId = $where['user_id'];
        $where = function ($query) use ($where) {
            $query->where('user_id', $where['user_id']);
            $query->where('status', 1);
            $share_ids = ForeignSpeakerShareLog::where('user_id', $where['user_id'])->pluck('collection_id');
            if (!empty($share_ids)) {
                $query->orWhereIn('id', $share_ids);
            }
        };

        $list = $this->where($where)->select('id', 'name', 'sort', 'user_id')->orderBy('id', 'desc')->get();
        foreach ($list as $key => &$val) {
            $val['count'] = ForeignSpeakerCollectionPivot::where('collection_id', $val['id'])->count();
            $val['share'] = ($val['user_id'] ==  $userId) ? 0 : 1;
        }

        return $list;
    }


    /**
     * 获取合集列表
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2022-08-17
     * @param int $id
     * @param int $page
     * @param int $limit
     * @param array $where
     * @return void
     */
    public function getCollectionListById($id, $page, $limit, $where = [])
    {
        $info = $this->find($id);

        $where = function ($query) use ($where, $info) {
            $query->where('eb_foreign_speaker_collection_pivot.user_id', $info->user_id);
            $query->where('status', 1);
            if (isset($where['name']) && $where['name'] != '') {
                $query->where('name', 'like', '%' . $where['name'] . '%');
            }
        };

        if (empty($info)) {
            return fail_message('未找到合集');
        }
        // $data = $info->guest_collection_pivot()->where($where)->paginate($limit)->toArray();orderByRaw("FIELD(status, " . implode(", ", [1, 0, 2]) . ")")->orderBy('foreign_speaker_collection_pivot.order', 'desc')
        $data = $info->guest_collection_pivot()->where($where)->orderByRaw("FIELD(eb_foreign_speaker_collection_pivot.order, " . implode(", ", [1, 2, 3, 4, 5, 6, 0]) . ")")->paginate($limit)->toArray();
        // dd($data);
        // return $data;
        $data = ['total' => $data['total'], 'current_page' => $data['current_page'], 'page_size' => $data['per_page'], 'pages' => ceil($data['total'] / $data['per_page']), 'list' => $data['data'], 'collection_name' => $info->name];
        return $data;
        // return ['total' => $data['total'], 'current_page' => $data['current_page'], 'page_size' => $data['per_page'], 'pages' => ceil($data['total'] / $data['per_page']), 'list' => $data['data'], 'collection_name' => $info->name];
        // $list = $this->paginate($page, $limit, $where, ['id', 'name', 'photo', 'sort', 'created_at']);
    }


    /**
     * 判断是否是第一次创建合集或者长时间没有登录过
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2022-09-28
     * @param [type] $where
     * @param boolean $isLongTime
     * @return boolean
     */
    public function isFirst($where, $isLongTime = false)
    {
        $userid = $where['user_id'];
        if (!$isLongTime) {
            // 查询今日数据
            $today_list = UserSign::where('userid', $userid)->whereDate('created_at', Carbon::now()->toDateString())->orderBy('created_at', 'desc')->first();

            $where = function ($query) use ($where) {
                $query->where('user_id', $where['user_id']);
                $query->where('status', 1);
            };

            $list = $this->where($where)->count();

            // 如果今日已经记录了，并且|| !empty($today_list)
            if ($list >= 1 || !empty($today_list)) {
                return ['is_first' => 0]; // 1提示  0不提示
            } else {
                UserSign::create([
                    'userid' => $userid,
                    'title' => '记录是否查看合集',
                    'number' => '0',
                    'balance' => '0',
                ]);
                return ['is_first' => 1];
            }
        } else {
            $member = User::find($where['user_id']);
            if ((time() - $member['last_login_time']) > (86400 * 24)) { //如果24天没有登陆过提示
                return ['is_first' => 1];
            } else {
                return ['is_first' => 0];
            }
        }
    }



    /**
     * 获取合集列表
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2022-08-17
     * @param int $id
     * @param int $page
     * @param int $limit
     * @param array $where
     * @return void
     */
    public function createPpt($id)
    {
        $info = $this->find($id);
        $where = function ($query) use ($info) {
            $query->where('eb_foreign_speaker_collection_pivot.user_id', $info->user_id);
            $query->where('status', 1);
        };

        if (empty($info)) {
            return fail_message('未找到合集');
        }

        $data['list'] = $info->guest_collection_pivot()->where($where)->orderByRaw("FIELD(eb_foreign_speaker_collection_pivot.order, " . implode(", ", [1, 2, 3, 4, 5, 6, 0]) . ")")->get()->toArray();



        $data['collection_name'] = $info->name;
        return $data;
    }
}
